package com.mystnihon.actions;

import java.io.IOException;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONArray;

import ca.benow.transmission.model.TorrentStatus.TorrentField;

import com.mystnihon.models.Seedbox;
import com.opensymphony.xwork2.ActionSupport;

public class SeedboxsDataAction extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Session object
	 */
	private Map<String, Object> session;

	private String the = "Parish";
	private int id;

	public void setId(int id) {
		this.id = id;
	}

	public String getThe() {
		return this.the + " " + id;
	}

	public String execute() {
		System.out.println("Execute !");
		return "success";
	}

	/**
	 * Return the seedbox object stored in session.
	 * 
	 * @return seedbox Seedbox
	 */
	public Seedbox returnSelectedSeedbox() {
		if (session != null) {
			if (session.get("selectedSeedbox") != null) {
				return (Seedbox) session.get("selectedSeedbox");
			}
		}
		return null;
	}

	public String getTorrentList() {
		System.out.println("List torrents.");

		Seedbox seedbox = returnSelectedSeedbox();
		System.out.println("Get seedbox : " + seedbox.getName() + ".");
		if (seedbox != null) {
			try {
				if (seedbox.connect()) {
					JSONArray json = new JSONArray();
					json.put(seedbox.getAllTorrents(myfields));
					return json.toString();
				} else {
					System.err.println("Couldn't connect.");
					return null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.err.println("Couldn't retrieve seedbox object from session.");
		return null;

	}

	@Override
	public void setSession(Map<String, Object> obj) {
		this.session = obj;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	/**
	 * Requested fields
	 * 
	 */
	private TorrentField[] myfields = new TorrentField[] { TorrentField.id,
			TorrentField.name, TorrentField.status, TorrentField.percentDone,
			TorrentField.totalSize, TorrentField.doneDate,
			TorrentField.isFinished, TorrentField.files,
			TorrentField.rateDownload, TorrentField.rateUpload };
}
